<template>
	<view class="nicknametitle">
		请输入宝宝昵称
	</view>
	<view class="nickname-item">
		<uni-row>
			<uni-col :span="6">
				<template v-if="!formData.avatar">
				          <uni-icons 
				            class="photo" 
				            type="camera" 
				            size="50" 
				            @click="showActionSheet"
				          ></uni-icons>
				        </template>
				        <template v-else>
				          <image 
				            :src="formData.avatar" 
				            class="avatar" 
				            mode="aspectFill"
				            @click="showActionSheet"
				          ></image>
				        </template>
			</uni-col>
			<uni-col :span="18">
				<input v-model="formData.nickname" class="nickename-input" type="text" placeholder="输入宝宝昵称 , 2-10个字符">
			</uni-col>
		</uni-row>
	</view>
	<view class="birthdaytitle">
		请选择宝宝出生日期
	</view>
	<view class="list-cell">
		<view class="list-cell-left">
			当前选择
		</view>
		<view class="list-cell-db">
			<picker mode="date" :value="formData.birthday" :start="startDate" :end="endDate" @change="bindDateChange">
				<view class="uni-input">{{formData.birthday}}</view>
			</picker>
		</view>
	</view>
	<button type="default" class="ensure-btn" @click="submitForm">确定</button>
</template>


<script setup>
	import {
		ref,
		computed,
		onMounted
	} from 'vue';

	// 定义响应式变量
	const formData = ref({
		avatar: '',
		nickname: '',
		gender: '',
		birthday: getDate({format: true}),
	});

	// 在页面加载时获取传递的性别参数
	onMounted(() => {
		const pages = getCurrentPages();
		const currentPage = pages[pages.length - 1];
		const eventChannel = currentPage.$page.options;
		formData.value.gender = eventChannel.gender;
	});

	// 计算属性
	const startDate = computed(() => getDate('start'));
	const endDate = computed(() => getDate('end'));

	function bindDateChange(e) {
		formData.value.birthday = e.detail.value;
	}

	function getDate(type) {
		const now = new Date();
		let year = now.getFullYear();
		let month = now.getMonth() + 1;
		let day = now.getDate();

		if (type === 'start') {
			year -= 60;
		} else if (type === 'end') {
			year += 2;
		}

		month = month > 9 ? month : `0${month}`;
		day = day > 9 ? day : `0${day}`;

		return `${year}-${month}-${day}`;
	}

	// 提交表单方法
	const submitForm = async () => {
		
		if (!formData.value.avatar) {
			uni.showToast({
				title: '请上传宝宝头像',
				duration: 2000
			});
			return;
		}
		
		if (!formData.value.nickname) {
			uni.showToast({
				title: '请填写宝宝昵称',
				duration: 2000
			});
			return;
		}
		if (formData.value.nickname.length < 2 || formData.value.nickname.length > 10) {
			uni.showToast({
				title: '宝宝昵称的长度必须是2-10位',
				duration: 2000
			});
			return;
		}
		
		if (!formData.value.birthday) {
			uni.showToast({
				title: '请选择宝宝出生日期',
				duration: 2000
			});
			return;
		}
		
		uni.request({
		    method: 'POST',
		    url: 'http://localhost:9100/api/baby/save',
		    data: formData.value,
		    header: {
		        'bece_token': uni.getStorageSync('bece_token') 
		    },
		    success: (res) => {
		        console.log(res.data);
				if (res.data.code == 200) {
					formData.value = {};
					uni.showToast({
						title: '保存成功',
						duration: 2000
					});
					// 跳转页面
					uni.navigateTo({
						url: '/pages/baby/list/list'
					});
				} else {
					uni.showToast({
						title: res.data.msg,
						duration: 2000
					});
				}
		    }
		});
	};

	function showActionSheet() {
		uni.showActionSheet({
			itemList: ['拍照', '相册'],
			success: function(res) {
				if (res.tapIndex === 0) {
					// 拍照
					chooseImage('camera');
				} else {
					// 相册选择
					chooseImage('album');
				}
			}
		});
	}

	function chooseImage(sourceType) {
		uni.chooseImage({
			count: 1,
			sourceType: [sourceType],
			success: (res) => {
				// 上传图片
				uni.uploadFile({
					url: 'http://localhost:9100/api/upload/image', // 修改为实际的上传接口
					filePath: res.tempFilePaths[0],
					name: 'file',
					success: (res) => {
						let data = JSON.parse(res.data);
						formData.value.avatar = data.data;
						console.log(formData.value.avatar);
					},
					fail: (err) => {
						uni.showToast({
							title: '上传图片失败',
							duration: 2000
						});
					}
				});
			}
		});
	}
</script>


<style scoped>
	page {
		padding: 0 45rpx;
	}

	.nicknametitle {
		margin-top: 50rpx;
	}

	.nickname-item {
		margin-top: 30rpx;
		margin-left: 25rpx;
	}

	.nickename-input {
		margin-top: 20rpx;
		font-size: 30rpx;
	}

	.birthdaytitle {
		margin: 20rpx 0rpx;
	}

	.list-cell {
		display: flex;
		justify-content: space-around;
		padding: 20rpx 0rpx;
		border: #f1f1f1 solid 4rpx;
		border-radius: 20rpx;
	}

	.list-cell-db {}

	.ensure-btn {
		margin-top: 650rpx;
		color: #fff !important;
		background-color: #666ee8 !important;
		border-radius: 100rpx;
	}


	.avatar {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		margin-top: 10rpx;
		cursor: pointer;
	}

	.photo {
		display: block;
		margin-bottom: 10rpx;
		cursor: pointer;
	}
</style>